import heapq

from querier.esquerier import ElasticSearchQuerier
import json
import operator

WORDCLOUD_TOP_N = 100


class Class1WordCloudQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(Class1WordCloudQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args['class1_id']
        res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        if res['found']:
            class1_id=res['_source']['class1_id']
            class1_name= res['_source']['class1_name']
            keywords = res['_source']['keywords'][0:WORDCLOUD_TOP_N]
            weight = res['_source']['weight'][0:WORDCLOUD_TOP_N]
            len_keywords = len(keywords)
            len_weight = len(weight)
            length = len_keywords if len_keywords <= len_weight else len_weight
            ret = [{"text": keywords[i], "weight": weight[i]} for i in range(0, length)]
            return{
                "class1_id":class1_id,
                "class1_name":class1_name,
                "keywords":ret
            }
        return {'message': 'class1_id=%s not found.' % id_}
